from django.db import models
import datetime

from django.utils import timezone

from backend import settings


# 仓库模型
class Repository(models.Model):
    # 仓库URL
    url = models.TextField()

    # 仓库名称
    name = models.TextField()

    # 仓库所在平台
    platform = models.TextField()

    # 哈希值
    hash = models.TextField()

    # README文件内容
    readme = models.TextField(blank=True, null=True)

    # 上次更新时间
    updated = models.DateTimeField(default=datetime.datetime.fromtimestamp(0, tz=timezone.utc if settings.USE_TZ else None))

    def __str__(self):
        if self.name is None:
            return ""
        return self.platform + ":" + self.name


# Commit模型
class Commit(models.Model):
    class Meta:
        ordering = ("-time",)

    # Commit Hash
    hash = models.TextField()

    # Commit 内容
    content = models.TextField()

    # Commit 提交时间
    time = models.DateTimeField()

    # 所关联的 Repository
    repository = models.ForeignKey(Repository, null=False, on_delete=models.CASCADE)

    # 程序分析结果
    result_sa = models.TextField(blank=True, null=True)

    # 自然语言处理结果
    result_nlp = models.TextField(blank=True, null=True)

    # 状态
    """
        0 - 正在从仓库中取得信息
        1 - 调用代码分析模块
        2 - 调用自然语言处理模块
        3 - 完成
    """
    status = models.IntegerField(null=False, default=0)

    def __str__(self):
        return f"{self.repository.__str__()} > {self.hash}"

# 文件修改对象
class File(models.Model):
    # 文件完整路径 ( Repository 内的路径)
    path = models.TextField(db_index=True)

    # 所关联的 Commit
    # ** 此处仅保留产生差异的文件 **
    commit = models.ForeignKey(Commit, null=False, on_delete=models.CASCADE)

    # 文件是否为二进制，如果是二进制，则下方内容均为空
    binary = models.BooleanField(default=False)

    # 修改前文件内容
    content_old = models.TextField(blank=True, null=True)

    # 修改后文件内容
    content_new = models.TextField(blank=True, null=True)

    # 修改类型
    type = models.TextField(blank=True, null=True)

    # 修改差异
    diff = models.TextField(blank=True, null=True)

    """
    注释信息
    ** 由代码分析模块提取,以JSON格式存储 **
    格式
    {
        "750-752": "enterRegion - Called back from after crossing a scheduling boundary. [begin, end) includes all instructions in the region, including the boundary itself and single-instruction regions",
        "796-798": "PostMachineScheduler::runOnMachineFunction. This is a simplified driver that does not consider liveness or register pressure. It is useful for PostRA scheduling and potentially other custom schedulers.",
    }
    """
    comments = models.TextField(blank=True, null=True)


    """
    架构信息所在行
    ** 由代码分析模块提取,以JSON格式存储 **
    格式
    [2,3,4]
    """
    arch_line = models.TextField(blank=True, null=True)

    def __str__(self):
        return f"{self.commit.repository.__str__()} > {self.commit.hash} > {self.path} "


